<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Potevio集成平台</title>
</head>
<body>
<div th:fragment="main" id="organization" class="organization">
    <link rel="stylesheet" th:href="@{/css/organizationGroup/zTree/zTreeStyle/awesome.css}">
    <link rel="stylesheet" th:href="@{/css/organizationGroup/organization.css}">
    <link rel="stylesheet" th:href="@{/assets/jqGrid/css/jqgridReset.css}">
    <div class="row">
        <div class="col-xs-3 organizationTree">
            <div class="organization-content">
                <div class="organization-title"><i class="iconfont">&#xe606;</i>组织机构</div>
                <div class="organization-tree">
                    <ul id="treeDemo" class="ztree"></ul>
                </div>
            </div>
        </div>
        <div class="col-xs-9 operation">
            <div class="operation-content">
                <div class="operation-header clearfix">
                    <form class="navbar-form" onsubmit="return false;">
                        <div class="groups form-group">
                                <span class="find">
                                    <i class="fa fa-search"></i>
                                </span>
                            <input type="text" class="form-control search" id="search" placeholder="请输入组织机构名称"
                                   maxlength="25">
                        </div>
                        <input type="button" value="搜索" class="btn btn-primary nav-btn" id="searchUser">
                    </form>
                    <a href="#platform-organizationGroup-addOrganization" id="addOrganization"
                       class="addUser btn btn-primary nav-btn"
                       th:if="${#authorization.expression('hasAuthority(''createOrganization'')')}">新建组织机构</a>
                </div>
                <div class="operation-table" id="operation-table">
                    <table id="list2"></table>
                    <div id="gridpager"></div>
                </div>
            </div>
        </div>
    </div>
    <!--删除提示模态框  -->
    <div id="deleteNotice" class="modal fade bs-example-modal-sm notice" tabindex="-1" role="dialog"
         aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title" id="myModalLabel">操作提示</h3>
                </div>
                <div class="modal-body">
                    确认删除此条数据吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="deleteData">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>

        <script th:src="@{/assets/jqGrid/js/grid.locale-cn.js}"></script>
        <script th:src="@{/assets/jqGrid/js/jquery.jqGrid.src.js}"></script>
        <script th:inline="javascript">
            // 权限控制
            var hasQueryOrganization = [[${#authorization.expression('hasAuthority(''queryOrganization'')')}]];
            var hasModifyOrganization = [[${#authorization.expression('hasAuthority(''modifyOrganization'')')}]];
            var hasDeleteOrganization = [[${#authorization.expression('hasAuthority(''deleteOrganization'')')}]];
            // jqgrid表格配置
            // 使jqgrid的宽和高自适应父元素
            var parentHeight, parentWidth;
            $(function () {
                //页面加载完成之后执行
                parentHeight = $("#operation-table").height() * 1 - 85;
                parentWidth = $("#operation-table").width() * 1 + 14;
                pageInit();
            });

            // 初始化jqGrid
            function pageInit() {
                // 操作按钮
                function operation(cellvalue, options, rowObject) {
                    var amend = "";
                    var deleted = "";
//                        console.log("rowO:"+rowObject);
//                        console.log(rowObject);
                    if (hasModifyOrganization) {
                        amend = "<input class='btn btn-primary btn-xs modify' type='button' value='修改'>&nbsp;";
                    }
                    if (hasDeleteOrganization && rowObject.code != "000") {
                        deleted = "<input class='btn btn-danger btn-xs del' type='button' value='删除' data-toggle='modal' data-target='.bs-example-modal-sm'>";
                    }
                    return amend + deleted;
                }

                //创建jqGrid组件
                jQuery("#list2").jqGrid({
                    url: contextPath + "/Organization/queryOrganizationJqg",
                    datatype: "json",
                    height: parentHeight,
                    width: parentWidth,
                    colNames: ['组织机构ID', '组织名称', '组织编码', '描述', '父机构ID', '操作'],
                    colModel: [
                        {name: 'id', index: 'id', sorttype: "int",hidden: true},
                        {name: 'name', index: 'name'},
                        {name: 'code', index: 'code', hidden: true},
                        {name: 'description', index: 'description', sorttype: "string"},
                        {name: 'parentId', index: 'parentId', sorttype: "string", hidden: true},
                        {name: 'operation', index: 'id', sortable: false, align: "center", formatter: operation}
                    ],
                    sortname: 'id',
                    sortorder: 'asc',
                    viewrecords: true,
//                    multiselect: true,
                    rowNum: 20,
                    rowList: [20, 50, 100],
                    pager: "#gridpager"
                });
                /*创建jqGrid的操作按钮容器*/
                jQuery("#list2").jqGrid('navGrid', '#gridpager', {
                    edit: false,
                    add: false,
                    del: false,
                    search: false
                });
                //浏览器窗口发生变化时同时变化DIV高度
                var timer = 0;
                $(window).resize(function () {
                    timer = setTimeout(function () {
                        $("#list2").setGridWidth($('#operation-table').width() * 1 + 14);
                        $("#list2").setGridHeight($('#operation-table').height() * 1 - 85);
                        clearTimeout(timer);
                    }, 260);
                });
            };
            // 侧边栏缩小时，实时的给jqgrid的宽和高赋值
            $("#asidebarSwitch").on('click', function () {
                var time = 0;
                var set = setInterval(function () {
                    $("#list2").setGridWidth($('#operation-table').width() * 1 + 14);
                    $("#list2").setGridHeight($('#operation-table').height() * 1 - 85);
                    time++;
                    if (time >= 200) {
                        clearInterval(set);
                    }
                }, time);
            });

            // zTree获取组织关系树结构
            var zTreeObj;
            var zNodes;
            // zTree 的参数配置
            var setting = {
                view: {
                    dblClickExpand: true, // 取消双击展开事件
                },
                data: {
                    simpleData: {
                        enable: true, //是否开启异步加载模式
                    }
                },
                callback: {
                    onClick: onClick
                }
            };
            // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
            // 页面加载完成获取zTree数据
            $(document).ready(getZtree());

            // zTree加载数据
            function getZtree() {
                $.ajax({
                    url: contextPath + "/Organization/queryOrganizationTree",
                    type: "get",
                    cache: false,
                    dataType: "json",
                    success: function (data) {
                        //console.log(data);
                        if (data.code == 2) {
                            $(".organization-tree").html(data.message);
                            return;
                        }
                        zNodes = data;
                        zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                        updateType();
                    },
                    error: function (data) {
                        toastr.error("请求失败，请稍后再试!", data.message);
                    }
                });
            }

            // 点击树节点为 jqgrid 加载数据
            function onClick(e, treeId, treeNode) {
                var userId = treeNode.organizationCode;
                $("#list2").setGridParam({
                    url: contextPath + "/Organization/queryOrganizationJqg",
                    postData: {
                        queryCond: {
                            orgIdCondition: userId,
                            orgName: ''
                        }
                    }
                }).trigger("reloadGrid");
            };

            function updateType() {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    nodes = zTree.transformToArray(zTree.getNodes());
                for (var i = 0, l = nodes.length; i < l; i++) {
                    var num = nodes[i].children ? nodes[i].children.length : 0;
                    if (num.length == 0 || num.length == undefined) {
                        nodes[i].name = nodes[i].name;
                        zTree.updateNode(nodes[i]);
                    } else {
                        nodes[i].name = nodes[i].name.replace(/ \(.*\)/gi, "") + " (" + num + ")";
                        zTree.updateNode(nodes[i]);
                    }
                }
            };

            // 搜索
            $("#searchUser").on('click', function () {
                orgName = $('#search').val();
                $("#list2").setGridParam({
                    url: contextPath + "/Organization/queryOrganizationJqg",
                    postData: {
                        queryCond: {
                            orgIdCondition: '',
                            orgName: orgName
                        }
                    },
                    page:1
                }).trigger("reloadGrid");
            });
            $('#search').on('keypress', function (event) {
                var theEvent = window.event || event;
                var code = theEvent.keyCode || theEvent.which;
                var orgName = $('#search').val();
                if (code == 13) {
                    $("#list2").setGridParam({
                        url: contextPath + "/Organization/queryOrganizationJqg",
                        postData: {
                            queryCond: {
                                orgIdCondition: '',
                                orgName: orgName
                            }
                        },
                        page:1
                    }).trigger("reloadGrid");
                }
            });
            // 修改 删除
            var data;
            $("#list2").on('click', '.modify,.del', function () {
                var parentId = $(this).parent().parent().attr('id');
                var ids = $("#list2").jqGrid('getRowData', parentId);

                delete ids.operation;
                if ($(this).hasClass("modify")) {
                    $.cookie('modifyData', JSON.stringify(ids));
                    window.location.hash = "platform-organizationGroup-modifyOrganization";
                } else {
                    data = JSON.stringify(ids);

                }
            });


            // 点击删除
            $("#deleteData").on('click', function () {
                $.ajax({
                    url: contextPath + '/Organization/deleteOrganization',
                    type: "delete",
                    contentType: "application/json",
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        if (data.code == 1) {

                            $('#deleteNotice').modal('hide');
                            toastr.success('删除成功！');
                            getZtree();
//                            var userId = treeNode.organizationCode;
                            $("#list2").setGridParam({
                                url: contextPath + "/Organization/queryOrganizationJqg",
                                postData: {
                                    queryCond: {
                                        orgIdCondition: '',
                                        orgName: ''
                                    }
                                },
                                page: 1

                            }).trigger("reloadGrid");
                        }

                     else {
                            toastr.error(data.message);
                        }
                    },
                    error: function () {
                        toastr.error('操作失败！');
                    }
                });
            });
        </script>
    </div>
</body>
</html>